#include "Simulation.h"

Simulation::Simulation(ChessBoardController * boardController, ChessPanelRecController * panelController) :
    chessBoardController(boardController),
    panelController(panelController),
    paused(false),
    stopped(false)
{
    chessBoard = chessBoardController->getChessBoard();

    connect(panelController, SIGNAL(startSimulation()), this, SLOT(startSimulation()), Qt::QueuedConnection);
    connect(panelController, SIGNAL(pause()), this, SLOT(pause()), Qt::QueuedConnection);
    connect(panelController, SIGNAL(resume()), this, SLOT(resume()), Qt::QueuedConnection);
}

void Simulation::setGameRecord(GameRecord *record)
{
    gameRecord = record;
}

void Simulation::startSimulation()
{
    start();

}

void Simulation::pause()
{
    paused = true;
}

void Simulation::resume()
{
    paused = false;
}

void Simulation::stop()
{
    stopped = true;
}

void Simulation::run()
{
    Moves * moves = gameRecord->getGameMoves()->getMoves();
    int i = 0;

    foreach(Move * move, *moves) {
        //pauzowanie i przerywanie
        while(paused) {}
        if(stopped) { stopped = false; break; }

        if(move->getSquareBegin() != "" && move->getSquareEnd() != "") { //wtf o_O
            QString comm =  QString::number(i) + " (" + move->getName() + "): ruch z pola " + move->getSquareBegin() + " na pole " + move->getSquareEnd();
            Console::print(comm);

            if(move->getName() == "O-O") {
                chessBoard->move(move->getSquareBegin(), move->getSquareEnd());
                chessBoard->move(move->getCastlingBegin(), move->getCastlingEnd());
            } else {
                chessBoard->move(move->getSquareBegin(), move->getSquareEnd());
            }

            QThread::sleep(1);
            i++;
        } else break;
    }
}
